<template>
  <!-- 原材料采购配置表表单弹窗 -->
  <el-dialog
    v-model="visibleDialog"
    :title="props.title"
    width="60%"
    draggable
    @close="closeDialog"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="160">
      <el-row>
        <el-col :span="8">
          <el-form-item label="分类" prop="classification">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.classification"
              placeholder="请输入分类"
              clearable
            />

            <span v-else>{{ formData.classification }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="物料名称"
            prop="materialName"
            label-width="160px"
          >
            <el-input
              v-model="formData.materialName"
              placeholder="请选择物料"
              clearable
              readonly
              style="width: 100%"
              @click="showWorkOrderSelect"
            >
              <template #append>
                <el-button type="success" plain @click="showWorkOrderSelect">
                  选择
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单位" prop="unit">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.unit"
              placeholder="请选择计量单位"
              clearable
              disabled
              style="width: 100%"
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList(
                  'MeasurementUnit'
                )"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <span v-else>{{
              useDictionary("MeasurementUnit", String(formData.unit))
            }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="采购周期" prop="purchasingCycle">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.purchasingCycle"
              placeholder="请输入采购周期"
              clearable
            />

            <span v-else>{{ formData.purchasingCycle }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="采购影响(产能)" prop="produce">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.produce"
              placeholder="请输入采购影响(产能)"
              clearable
            />

            <span v-else>{{ formData.produce }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="采购影响(天气)" prop="weather">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.weather"
              placeholder="请输入采购影响(天气)"
              clearable
            />

            <span v-else>{{ formData.weather }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="采购影响(质量异常)" prop="quality">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.quality"
              placeholder="请输入采购影响(质量异常)"
              clearable
            />

            <span v-else>{{ formData.quality }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="保质期（月）" prop="shelfLife">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.shelfLife"
              placeholder="请输入保质期（月）"
              clearable
            />

            <span v-else>{{ formData.shelfLife }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="最小采购量" prop="minimumPurchaseQuantity">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.minimumPurchaseQuantity"
              placeholder="请输入最小采购量"
              clearable
            />

            <span v-else>{{ formData.minimumPurchaseQuantity }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.remarks"
              placeholder="请输入备注"
              clearable
            />

            <span v-else>{{ formData.remarks }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="启用状态" style="width: 310px" prop="enabled">
            <el-radio-group v-model="formData.enabled" v-if="!props.isReadonly">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
            <span v-else>{{ formData.enabled == 1 ? "是" : "否" }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
    <!--物料选择-->
    <conten-select
      :visible="selectDialogSELECT.visible"
      @change-visible="changeVisibleSELECT"
      :brekList="brekList"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { useDictionary } from "@/utils/useTable";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MESMESPURCHASEMATERIALCONFIGADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  materialId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  materialCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  materialName: [
    { required: true, message: "请输入物料名称", trigger: ["blur", "change"] },
  ],
  classification: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  unit: [],
  purchasingCycle: [{ validator: validateNumber, trigger: "blur" }],
  safetyFactor: [{ validator: validateNumber, trigger: "blur" }],
  shelfLife: [{ validator: validateNumber, trigger: "blur" }],
  minimumPurchaseQuantity: [{ validator: validateNumber, trigger: "blur" }],
  produce: [{ validator: validateNumber, trigger: "blur" }],
  weather: [{ validator: validateNumber, trigger: "blur" }],
  quality: [{ validator: validateNumber, trigger: "blur" }],
  createTime: [],
  createdUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  createdUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  lastUpdateTime: [],
  lastUpdatedUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  lastUpdatedUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  enabled: [],
  deleted: [],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  version: [],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  classification: "",
  unit: "",
  purchasingCycle: "",
  safetyFactor: "",
  shelfLife: "",
  minimumPurchaseQuantity: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
  remarks: "",
  version: "",
  produce: "",
  weather: "",
  quality: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        materialId,
        materialCode,
        materialName,
        classification,
        unit,
        purchasingCycle,
        safetyFactor,
        shelfLife,
        minimumPurchaseQuantity,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        remarks,
        version,
        produce,
        weather,
        quality,
      } = newVal;
      Object.assign(formData, {
        id,
        materialId,
        materialCode,
        materialName,
        classification,
        unit,
        purchasingCycle,
        safetyFactor,
        shelfLife,
        minimumPurchaseQuantity,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        remarks,
        version,
        produce,
        weather,
        quality,
      });
      formData.unit = String(formData.unit);
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.materialId = "";
  formData.materialCode = "";
  formData.materialName = "";
  formData.classification = "";
  formData.unit = "";
  formData.purchasingCycle = "";
  formData.safetyFactor = "";
  formData.shelfLife = "";
  formData.minimumPurchaseQuantity = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.remarks = "";
  formData.produce = "";
  formData.weather = "";
  formData.quality = "";
  formData.version = "";
}

const loading = ref(false);

/** 原材料采购配置表保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/mes/mespurchasematerialconfig/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

//产品选择
const showWorkOrderSelect = () => {
  selectDialogSELECT.value.visible = true;
};
//选择物料弹窗
const selectDialogSELECT = ref({
  visible: false,
});
const changeVisibleSELECT = (val: boolean, data: any) => {
  selectDialogSELECT.value.visible = val;
  if (data) {
    formData.materialId = data.id;
    formData.materialCode = data.materialCode;
    formData.materialName = data.materialName;
    formData.unit = data.unit;
  }
};
// 回显的数据
const brekList = ref([]);

function validateNumber(rule: any, value: any, callback: (a?: any) => {}) {
  if (value == "") {
    callback();
  }
  if (isNaN(parseFloat(value)) && isFinite(value)) {
    callback(new Error("请输入数字"));
  } else if (!/^[+-]?\d+?(e[+-]?\d+)?$/.test(value)) {
    callback(new Error("请输入整数"));
  } else if (Number(value) <= 0) {
    callback(new Error("请输入大于0的值"));
  } else {
    callback();
  }
}
</script>
